<!--
 * @Description: 
 * @Date: 2020-12-15 17:18:19
 * @LastEditors: lother
 * @LastEditTime: 2021-01-04 16:52:19
 * @FilePath: \AccountOpening-H5\src\components\page\k-date.vue
-->
<template>
    <div>
        <van-field 
            :value="value"
            :label="list['title_'+langSuff]"
            :placeholder="$t('login.index.5638rk3g0080')+list['title_'+langSuff]"
            :required="required"
            :rules="rulesList">
            <template #input>
                <div class="center" style="width:100%">
                    <p>{{value?value:$t('login.index.5638rk3g0080')+list['title_'+langSuff]}}</p>
                    <input :type="list.type=='date'?'date':(list.type=='time'?'time':'datetime-local') " v-model="time"  class="date" @input="dateChanged">
                    <van-icon name="notes-o" :size="20"/>
                </div>
                <!-- <van-radio-group v-model="radios">
                    <van-radio v-for="(item) in columns" :key="item.value" :name="item.value" >
                        <div v-html="$backTitle(item['title_'+langSuff])"></div>
                        <template #icon="props">
                            <img class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
                        </template>
                    </van-radio>
                </van-radio-group> -->
            </template>
        </van-field>

        <!-- <van-field
        readonly
        clickable
        clearable
        name="datetimePicker"
        v-model="value"
        :label="list['title_'+langSuff]"
        :placeholder="'请选择'+list['title_'+langSuff]"
        @click="showPicker = true"
        :required="required"
        :rules="rulesList"
        />
        <van-popup v-model="showPicker" position="bottom">
            <van-datetime-picker
                v-model="date"
                :type="list.type=='date'?'date':'datetime'"
                :min-date="minDate"
                @confirm="onConfirm"
                @cancel="showPicker = false"
                :filter="filter"
            />
        </van-popup>
        <input type="date"> -->
    </div>
</template>
<script>
export default {
    name:"k-date",
    props:{
        val:{
            type:[String,Number],
            default:""
        },
        list:{
            type:Object,
            default:()=>{}
        },
        showTime:{
            type:Object,
            default:()=>{}
        }
    },
    computed:{
        required(){
            var boll = (this.list?.is_require)?true:false
            return boll
        },
        langSuff(){
            return this.$store.state.langSuff
        },
        rulesList(){
            var arr=[]
            if(this.list?.is_require){
                arr.push({ required: true, message: this.$t('login.index.5638rk3g0080')+this.list['title_'+this.langSuff] })
            }
            var rules  = this.list?.rule ?? [];
            for (let index = 0; index < rules.length; index++) {
                const item = rules[index];
                if(item.rule!==''){
                    arr.push({pattern:this.evalreg(item.rule) , message : item['error_tip_'+this.langSuff]})
                }
            }
            return arr
        }
    },
    data() {
        return {
            value:null,
            showPicker: false,
            date:null,
            minDate:new Date(new Date().getFullYear()-18,0,1,0,0),
            time:""
        }
    },
    created(){
        this.dateTime(this.val)
    },
    methods:{
        dateChanged(e){
            e.target.value = e.target.value.substr(0, 16);
            console.log(e.target.value)
            if(this.list.type=='date'){
                this.value = this.parseTime(e.target.value,'{y}/{m}/{d}')
            }else if(this.list.type=='datetime'){
                this.value=this.parseTime(e.target.value,'{y}/{m}/{d} {h}:{i}')
            }else if(this.list.type=='time'){
                this.value=e.target.value
            }
        },
        parseTime(time, cFormat) {
            if (arguments.length === 0) {
                return null
            }
            const format = cFormat || '{y}/{m}/{d} {h}:{i}:{s}'
            let date
            if (typeof time === 'undefined' || time === null || time === 'null' || time=='') {
                return ''
            } else if (typeof time === 'object') {
                date = time
            } else {
                if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
                time = parseInt(time)
                }
                if ((typeof time === 'number') && (time.toString().length === 10)) {
                time = time * 1000
                }
                
                date = new Date(time)
            }
            const formatObj = {
                y: date.getFullYear(),
                m: date.getMonth() + 1,
                d: date.getDate(),
                h: date.getHours(),
                i: date.getMinutes(),
                s: date.getSeconds(),
                a: date.getDay()
            }
            const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
                let value = formatObj[key]
                // Note: getDay() returns 0 on Sunday
                if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
                if (result.length > 0 && value < 10) {
                value = '0' + value
                }
                return value || 0
            })
            return time_str
        },
         evalreg(val) {
            val = val || "";
            return RegExp(val);
        },
        onConfirm(time) {
            let year = time.getFullYear();
            let month = this.pad(time.getMonth() + 1);
            let day = this.pad(time.getDate());
            var  hours  = this.pad(time.getHours())
            var  minutes  = this.pad(time.getMinutes())
            if(this.list.type=='date'){
                this.value = year + '/' + month + '/' + day ;
            }else{
                this.value = year + '/' + month + '/' + day +' '+hours +':'+ minutes;
            }
            this.showPicker = false;
        },
        filter(type, options) {
            if(JSON.stringify(this.showTime) !=='{}' && this.showTime !== undefined){
                var minHour = this.showTime.min || 0,
                    maxHour = this.showTime.max || 23;
                if (type === 'hour') {
                    var time = options.filter((option) => {
                         if( Number(option) >= (Number(minHour))  &&  Number(option) <= Number(maxHour) ){
                            return option
                        }
                    });
                    return time
                }
            }
             return options;
        },
        dateTime(val){
            this.value = val;

            // var str = val.split('/')
            // console.log(str)

            // var arr = val.split("/");

            // for (var i = 0; i < arr.length; i++) {
            //     var arr1 = arr[i].split(/\s+/);
            //     console.log(arr1)
            //     arr.push(arr1)
            //     // for (var j = 0; j < arr1.length; j++) {
            //         //     if (jQuery.trim(arr1[j]) != "") {
            //             //         resources += jQuery.trim(arr1[j]) + ",";
            //     //     }
            //     // }
            // }
                    // console.log(arr)


            // this.date =  new Date(str[0],(str[1]-1),str[2],(str[3]||0),(str[4]||0))
        },
        pad(str) {
            return +str >= 10 ? str : '0' + str
        }

    },
    watch:{
        value:{
            handler(val,old){
                this.$emit('update:val',val)
            }
        },
        val(val){
            this.dateTime(val)
        }
    }
}
</script>
<style lang="less" scoped>
    .date{
        border:none;
        background: none;
    }
    .center{
        position: relative;
        input{
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            position: absolute;
            opacity: 0;
        }
        p{
            // display: none;
            width: calc( 100% - 20px );
        }
    }
    // .date::-webkit-calendar-picker-indicator{
    //     display: none;
    // }
    // .date::-webkit-inner-spin-button { 
    //     visibility: hidden; 
    //     display: none;
    // }
    // input[type=date]::-webkit-inner-spin-button ,input[type=datetime-local]::-webkit-inner-spin-button  { visibility: hidden; }
    // input[type="date"]::-webkit-calendar-picker-indicator,input[type="datetime-local"]::-webkit-calendar-picker-indicator{
    //     display: none;
    // }
    
input[type="date"],input[type="datetime-local"]{
        width: calc( 100% - 20px );
        display: block;
		background-position: right;/*设置箭头位置*/
		padding-inline-start: 0px;
		-webkit-appearance: button;/*控制下拉箭头*/
	}
</style>